import {
	replyComments,
	findComments,
	postLikeComment
} from "../services/commentsService";


import {
	updateArticleByOption
} from '../services/articleService'

/**
 * 查询当前文章下的评论列表
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let FINDALL_COMMENTS = async (ctx, next) => {
	const { post_id, current_page = 1 } = ctx.request.query;
	let options = {
			sort : { create_at: -1 },
			page: current_page || 1
	};
	let query = {
			post_id
	};
	let comments = await findComments(query, options).catch((err) => { console.error(err) });
	ctx.success(comments, '获取数据成功');
};

/**
 * 写评论
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let INSERT_COMMENTS = async (ctx, next) => {
	const body = ctx.request.body;
	let comments =  await replyComments(body).catch((err) => { console.error(err) });
	await updateArticleByOption({name: 'id', value: body.post_id}, {type: 'comments'}).catch((err) => { console.error(err) });
	ctx.success(comments, '写入数据成功');
};

/**
 * 评论点赞
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 * @constructor
 */
let LIKE_COMMENT = async (ctx, next) => {
	const body = ctx.request.body;
	let comments = await postLikeComment(body).catch((err) => { console.error(err) });
	ctx.success(comments, '评论点赞成功');
};

module.exports = {
	'GET /api/comments': FINDALL_COMMENTS,
	'POST /api/comments/add': INSERT_COMMENTS,
	'POST /api/like': LIKE_COMMENT
};
